package com.jdone.compus.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class SignatureUtil {

    /**
     * 生成签名
     *
     * @param appSecret     应用密钥
     * @param timestamp     时间戳
     * @param randStr       随机字符串
     * @param encryptionType 加密类型（"sha1"或"md5"）
     * @return 生成的签名
     */
    public static String generateSignature(String appSecret, String timestamp, String randStr, String encryptionType) {
        // 将参数值按字典顺序排序
        String[] params = {appSecret, timestamp, randStr};
        Arrays.sort(params);

        // 将排序后的字符串拼接成一个字符串
        StringBuilder concatenated = new StringBuilder();
        for (String param : params) {
            concatenated.append(param);
        }

        // 根据加密类型进行加密
        return hash(concatenated.toString(), encryptionType);
    }

    /**
     * 根据指定的加密类型进行哈希运算
     *
     * @param input          要加密的字符串
     * @param encryptionType 加密类型（"sha1"或"md5"）
     * @return 加密后的字符串
     */
    private static String hash(String input, String encryptionType) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(encryptionType.toUpperCase());
            byte[] hashBytes = messageDigest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Unsupported encryption type: " + encryptionType, e);
        }
    }
}
